﻿using System;
using System.Collections.Generic;
using System.ComponentModel;
using System.Globalization;
using System.Linq;
using System.Text;
using System.Windows;
using System.Windows.Controls;
using System.Windows.Data;
using System.Windows.Documents;
using System.Windows.Input;
using System.Windows.Media;
using System.Windows.Media.Imaging;
using System.Windows.Navigation;
using System.Windows.Shapes;
using GMap.NET;

namespace MyPoints.UserControls
{
  /// <summary>
  /// Interaction logic for WptDetail.xaml
  /// </summary>
  public partial class WptDetail : UserControl
  {
    

    public delegate void ValueChangedDelegate(wptType sender);
    public event ValueChangedDelegate ValueCategoryChanged;
    public event ValueChangedDelegate ValueTitleChanged;
    public event ValueChangedDelegate ValueLocationChanged;

    private bool isCmbUpdate = false;

    [System.ComponentModel.EditorBrowsable(System.ComponentModel.EditorBrowsableState.Advanced)]
    private wptType _Value = null;
    ///<summary>
    /// Sets/gets Value value. Default value is null.
    ///</summary>
    public wptType Value
    {
      get
      {
        return (_Value);
      }
      set
      {
        if (_Value != null)
        {
          _Value.CategoryChanged -= _Value_CategoryChanged;
          _Value.TitleChanged -= _Value_TitleChanged;
          _Value.LocationChanged -= _Value_LocationChanged;
        }

        _Value = value;
        UpdateComboBox();
        this.DataContext = _Value;

        if (value != null)
        {
          _Value.CategoryChanged += _Value_CategoryChanged;
          _Value.TitleChanged += _Value_TitleChanged;
          _Value.LocationChanged += _Value_LocationChanged;
        }
      }
    }

    private void _Value_LocationChanged(wptType sender)
    {
      if (ValueLocationChanged != null)
        ValueLocationChanged(sender);
    }

    private void _Value_TitleChanged(wptType sender)
    {
      if (ValueTitleChanged != null)
        ValueTitleChanged(sender);
    }

    private void _Value_CategoryChanged(wptType sender)
    {
      if (ValueCategoryChanged != null)
        ValueCategoryChanged(sender);
    }

    private void UpdateComboBox()
    {
      isCmbUpdate = true;
      var cmbItems = Shared.model.TypeNames
        .OrderBy(q => q)
        .Select(q => new ComboBoxItem() { Content = q })
        .ToArray();

      cmbType.Items.Clear();
      foreach (var t in cmbItems)
      {
        cmbType.Items.Add(t);
        if (_Value != null && (t.Content as string) == _Value.type)
          cmbType.SelectedItem = t;
      }
      isCmbUpdate = false;
    }

    public WptDetail()
    {
      InitializeComponent();
    }

    private void cmbType_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      if (isCmbUpdate) return;
      if (cmbType.SelectedItem == null) return;

      txtType.Text = (cmbType.SelectedItem as ComboBoxItem).Content as string;

      BindingExpression binding = txtType.GetBindingExpression(TextBox.TextProperty);
      binding.UpdateSource();

    }

    private void btnTypeEditSwitch_Click(object sender, RoutedEventArgs e)
    {
      if (cmbType.Visibility == Visibility.Visible)
      {
        cmbType.Visibility = Visibility.Hidden;
        txtType.Visibility = Visibility.Visible;
      }
      else
      {
        cmbType.Visibility = Visibility.Visible;
        txtType.Visibility = Visibility.Hidden;
      }
    }

    private void cmbUpdateGpsBy_SelectionChanged(object sender, SelectionChangedEventArgs e)
    {
      string inText = "";

      int index = cmbUpdateGpsBy.SelectedIndex;
      if (index < 0)
        return;
      else if (index == 0)
        inText = Clipboard.GetText();

      InputWindow win = new InputWindow();
      win.Init();
      win.SetText(inText);
      bool? dialogResult = win.ShowDialog();

      if (dialogResult == null || dialogResult == false)
        return;

      GMap.NET.PointLatLng? newPoint = win.GetPointLatLng();

      if (newPoint == null)
        MessageBox.Show("Text was not recognized as GPS coordinates. No changes were made.", "...", MessageBoxButton.OK);
      else
      {
        Value.lat = (decimal)newPoint.Value.Lat;
        Value.lon = (decimal)newPoint.Value.Lng;
        MultiBindingExpression b = BindingOperations.GetMultiBindingExpression(txtGps, TextBox.TextProperty);
        b.UpdateTarget();

        //_Value_LocationChanged(Value);
        _Value.InvokeLocationChanged();
      }

      cmbUpdateGpsBy.SelectedIndex = -1;
    }

    private void mnuEdit_Click(object sender, RoutedEventArgs e)
    {
      EditImageWindow f = new EditImageWindow();
      f.Set(Value.img);
      var dr = f.ShowDialog();
      if (dr.HasValue && dr.Value)
      {
        var img = f.Get();
        UpdateValueImg(img, f.UrlFileWidth);
      }
    }

    private void UpdateValueImg(wptImageType obj, int maxSize)
    {
      if (obj.type == wptImageTypeType.Embedded)
      {
        System.Drawing.Image img = System.Drawing.Image.FromFile(obj.Value);
        System.Drawing.Bitmap newImg;
        if (img.Width > img.Height)
        {
          // sirsi nez vyssi
          if (img.Width > maxSize)
          {
            double ratio = (double)maxSize/ img.Width;
            ratio = img.Height * ratio;
            newImg = new System.Drawing.Bitmap(img, maxSize, (int)ratio);
          }
          else
            newImg = new System.Drawing.Bitmap(img);
        }
        else
        {
          // vyssi nez sirsi
          if (img.Height > maxSize)
          {
            double ratio = (double)maxSize / img.Height ;
            ratio = img.Width * ratio;
            newImg = new System.Drawing.Bitmap(img, (int)ratio, maxSize);
          }
          else newImg = new System.Drawing.Bitmap(img);
        }

        string s = Shared.ImageToString(newImg);
        obj.Value = s;
      } // if (obj.type == Embedded)

      Value.img = obj;
      imgImage.GetBindingExpression(Image.SourceProperty).UpdateTarget();
    } // private void UpdateValueImg()
  }
}
